//ServletContextTest.java
package com.ylaihui.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ServletContextTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = getServletConfig().getServletContext();
        //获取 web.xml 中配置的上下文参数 context-param
        String username = servletContext.getInitParameter("username");  // ylaihui
        System.out.println(username);

        //获取当前的工程路径， 格式: /工程路径
        String contextPath = servletContext.getContextPath();  // /06_Servlet
        System.out.println(contextPath);

        //  获取工程部署后在服务器上的绝对路径
        String realPath = servletContext.getRealPath("/");  // E:xxx...xxx\06_Servlet_war_exploded\
        System.out.println(realPath);
        String realPath1 = servletContext.getRealPath("/css");  // E:xxx...xxx\06_Servlet_war_exploded\css
        System.out.println(realPath1);
        String realPath2 = servletContext.getRealPath("/imgs");  // E:xxx...xxx\06_Servlet_war_exploded\imgs
        System.out.println(realPath2);

        // map  ServletContext 是在 web 工程部署启动的时候创建。
        // 在 web 工程停止的时候销毁，工程只要没重启， key中的值只要保存了，就一直存在。
        // 其他的 Servlet 也可以通过 getAttribute 获取 key 中保存的值
        servletContext.setAttribute("key1", "ylaihui");
        Object key1 = servletContext.getAttribute("key1");
        System.out.println(key1);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
